package com.zaofan.utils;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zaofan.constant.UrlConstant;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class ImageUpload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-ss");
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		// 判断提交的请求是否包含文�?
//		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		// 设置上传的保存路�?
		String uploadDir = getServletContext().getRealPath("/upload");
		if (uploadDir == null) {
			System.out.println("无法访问存储目录");
			return;
		}
		File fUploadDir = new File(uploadDir);
		if (!fUploadDir.exists()) {
			if (!fUploadDir.mkdir()) {
				System.out.println("无法创建存储目录!");
				return;
			}
		}
		Date date = new Date();
		String dsr = sdf.format(date);
		File dirfile = new File(fUploadDir, dsr);
		if (!dirfile.exists()) {
			if (!dirfile.mkdir()) {
				System.out.println("无法创建存储路径");
				return;
			}
		}

		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置内存中最大存�?5M，超过则保存到临时文件夹�?
		factory.setSizeThreshold(1024 * 1024 * 5);
		// 设置临时文件夹地�?
		factory.setRepository(new File("/"));
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 设置�?大上传的文件大小 3M
		upload.setSizeMax(1024 * 1024 * 3);
		String fileName = "";
		for (int k = 0; k < 100; k++) {
			if (k == 50) {
				continue;
			}
		}
		List<FileItem> items = null;
		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e1) {
			e1.printStackTrace();
		}
		Iterator<FileItem> iter = items.iterator();
		while (iter.hasNext()) {
			FileItem item = iter.next();
			if (item.isFormField()) {
				System.out.println("不是上传的文�?");
			} else {
				String[] strs = item.getName().split("\\.");
				fileName = sdf.format(date) + Math.random() * 30 + "." + strs[strs.length - 1];
				File nFile = new File(dirfile, fileName);
				try {
					item.write(nFile);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		String path = request.getContextPath();
//		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		String basePath = UrlConstant.HOST_URL+"/";
		String fileUrl = basePath + "upload/" + dsr + "/" + fileName;
		String callback = request.getParameter("CKEditorFuncNum");
		out.println("<script type=\"text/javascript\">");
		out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + fileUrl + "',''" + ")");
		out.println("</script>");
		out.flush();
		out.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
